package com.zjk.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zjk.Result;
import com.zjk.category.CategoryEntity;
import com.zjk.dto.CategoryDTO;
import com.zjk.mapper.CategoryMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: gfk
 * @create: 2022/10/19
 * @Description:
 * @FileName: CategoryService
 * @History:
 * @自定义内容：
 */
@Service
public class CategoryService {

    @Autowired(required = false)
    CategoryMapper categoryMapper;


    public List<CategoryDTO> findTreeCategoryDTO() {

        return categoryMapper.findAllCategoryDTO();
    }


    public List<CategoryDTO> listTreeCategoryDTO(){
        //所有的记录
        List<CategoryEntity> categoryEntityList = categoryMapper.selectList(Wrappers.emptyWrapper());

        List<CategoryDTO> collect =
                categoryEntityList.stream().filter(
                        (categoryEntity -> {
                            return categoryEntity.getParentCid() == 0;
                        })
                ).map(categoryEntity -> {
                    CategoryDTO dto = new CategoryDTO();
                    BeanUtils.copyProperties(categoryEntity,dto);
                    dto.setChildren(getChildren(categoryEntity,categoryEntityList));
                    return dto;
                }).collect(Collectors.toList());
        return collect;
    }

    public List<CategoryDTO> getChildren(CategoryEntity parent,List<CategoryEntity> categoryEntityList){
        List<CategoryDTO> collect = categoryEntityList.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() == parent.getCatId();
        }).map(categoryEntity1 -> {
            CategoryDTO dto = new CategoryDTO();
            BeanUtils.copyProperties(categoryEntity1, dto);
            dto.setChildren(getChildren(categoryEntity1, categoryEntityList));
            return dto;
        }).collect(Collectors.toList());

        if(collect.size() == 0){
            return null;
        }
        return collect;
    }


    public Result save(CategoryEntity categoryEntity){
        if(categoryEntity.getCatId()!=null){
            categoryMapper.updateById(categoryEntity);
            return new Result(true,1,"修改分类成功");
        }else{
            categoryMapper.insert(categoryEntity);
            return new Result(true,1,"添加分类成功");
        }
    }

    public CategoryEntity seleteById(Long catId){
        return categoryMapper.selectById(catId);
    }

    public Result deleteById(Long catId){
        categoryMapper.deleteById(catId);
        return new Result(true,1,"删除分类成功");
    }

}
